<template>
  <view class="stats-page">
    <!-- 页面标题 -->
    <view class="page-header animate-fade-up">
      <text class="page-title">数据统计</text>
      <text class="subtitle">了解你的生活规律</text>
    </view>
    
    <!-- 待办统计卡片 -->
    <view class="todo-stats-card animate-fade-up animate-delay-1">
      <text class="card-title">待办完成情况</text>
      <view class="todo-stats-row">
        <view class="stats-item">
          <text class="stats-num">{{ totalTodo }}</text>
          <text class="stats-label">总待办</text>
          <view class="stats-icon">📋</view>
        </view>
        <view class="stats-item">
          <text class="stats-num done-num">{{ doneTodo }}</text>
          <text class="stats-label">已完成</text>
          <view class="stats-icon">✅</view>
        </view>
        <view class="stats-item">
          <text class="stats-num">{{ doneRateFormatted }}</text>
          <text class="stats-label">完成率</text>
          <view class="stats-icon">📈</view>
        </view>
      </view>
      
      <!-- 进度条 -->
      <view class="progress-section">
        <view class="progress-info">
          <text class="progress-text">完成进度</text>
          <text class="progress-percentage">{{ doneRateFormatted }}</text>
        </view>
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: doneRate * 100 + '%' }"></view>
        </view>
      </view>
    </view>

    <!-- 心情统计切换 -->
    <view class="chart-tabs animate-fade-up animate-delay-2">
      <text :class="['chart-tab', { active: currentChart === 'pie' }]" @click="switchChart('pie')">
        <text class="tab-icon">🥧</text>
        心情占比
      </text>
      <text :class="['chart-tab', { active: currentChart === 'bar' }]" @click="switchChart('bar')">
        <text class="tab-icon">📊</text>
        每日心情
      </text>
      <text :class="['chart-tab', { active: currentChart === 'schedule' }]" @click="switchChart('schedule')">
        <text class="tab-icon">📅</text>
        心情课表
      </text>
    </view>

    <!-- 空数据提示 -->
    <view v-if="!hasDiaryData" class="empty-tip animate-fade-up animate-delay-3">
      <text class="empty-icon">📝</text>
      <text class="empty-text">暂无日记数据</text>
      <text class="empty-subtext">快去记录你的心情吧～</text>
      <button class="go-write-btn" @click="navigateToWriteDiary">立即写日记</button>
    </view>

    <!-- 饼图：心情占比 -->
    <view v-else-if="currentChart === 'pie'" class="chart-container animate-fade-up animate-delay-3">
      <text class="chart-title">心情分布占比</text>
      <text class="chart-subtitle">分析你的情绪变化</text>
      <!-- 添加条件渲染确保数据有效 -->
      <qiun-data-charts 
        v-if="pieChartData.series && pieChartData.series.length"
        type="pie"
        :chartData="pieChartData"
        width="700rpx"
        height="400rpx"
        :opts="pieChartOpts"
        canvasId="pie-chart"
      />
      <view v-else class="no-data-tip">
        <text class="no-data-icon">📊</text>
        <text>暂无心情数据</text>
      </view>
    </view>

    <!-- 柱形图：一周每日心情分布 -->
    <view v-else-if="currentChart === 'bar'" class="chart-container animate-fade-up animate-delay-3">
      <text class="chart-title">近7天心情趋势</text>
      <text class="chart-subtitle">查看每日情绪变化</text>
      <qiun-data-charts 
        v-if="barChartData.series && barChartData.series.length"
        type="column"
        :chartData="barChartData"
        width="700rpx"
        height="400rpx"
        :opts="barChartOpts"
        canvasId="bar-chart"
      />
      <view v-else class="no-data-tip">
        <text class="no-data-icon">📊</text>
        <text>暂无心情数据</text>
      </view>
    </view>

    <!-- 课表式心情：模拟一周7天网格 -->
    <view v-else-if="currentChart === 'schedule'" class="schedule-container animate-fade-up animate-delay-3">
      <text class="chart-title">心情课表</text>
      <text class="chart-subtitle">一周情绪变化一览</text>
      <!-- 星期表头 -->
      <view class="schedule-header">
        <text class="weekday" v-for="weekday in weekdays" :key="weekday">{{ weekday }}</text>
      </view>
      <!-- 心情网格（模拟3个时段：早/中/晚） -->
      <view class="schedule-grid">
        <view v-for="(day, dayIdx) in 7" :key="dayIdx" class="day-column">
          <view 
            v-for="(slot, slotIdx) in 3" 
            :key="slotIdx" 
            class="mood-slot"
            :style="{ backgroundColor: getMoodColor(scheduleMoods[dayIdx][slotIdx]) }"
            @click="showMoodDetail(scheduleMoods[dayIdx][slotIdx], dayIdx, slotIdx)"
          >
            <text class="mood-text">{{ scheduleMoods[dayIdx][slotIdx] || '-' }}</text>
          </view>
        </view>
      </view>
      <!-- 时段说明 -->
      <view class="time-slots">
        <text class="time-slot">早晨</text>
        <text class="time-slot">下午</text>
        <text class="time-slot">晚上</text>
      </view>
      <!-- 颜色图例 -->
      <view class="mood-legend">
        <view class="legend-item" v-for="(color, mood) in moodColorMap" :key="mood">
          <view class="color-block" :style="{ backgroundColor: color }"></view>
          <text>{{ mood }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getStorage } from '@/utils/storage'

export default {
  data() {
    return {
      currentChart: 'pie',
      totalTodo: 0,
      doneTodo: 0,
      doneRate: 0,
      pieChartData: { series: [] }, // 初始化空数组避免undefined
      barChartData: { categories: [], series: [] },
      scheduleMoods: [],
      weekdays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      moodColorMap: {
        开心: '#FF6B6B',
        疲惫: '#4ECDC4',
        学习: '#FFD166',
        日常: '#6A0572',
        emo: '#1A535C'
      },
      pieChartOpts: {
        type: 'pie',
        padding: [10, 10, 10, 10],
        legend: {
          show: true,
          position: 'bottom',
          align: 'center'
        },
        title: {
          name: '心情分布占比',
          fontSize: 16
        },
        // 修复微信小程序兼容性配置
        pixelRatio: 1,
        forceUtf8Encoding: true
      },
      barChartOpts: {
        type: 'column',
        padding: [10, 10, 10, 10],
        xAxis: {
          disableGrid: true,
          labelCount: 7
        },
        yAxis: {
          name: '数量',
          gridType: 'dash',
          min: 0
        },
        legend: {
          show: true,
          position: 'bottom'
        },
        title: {
          name: '近7天心情趋势',
          fontSize: 16
        },
        pixelRatio: 1,
        forceUtf8Encoding: true
      }
    }
  },
  computed: {
    doneRateFormatted() {
      return this.totalTodo === 0 
        ? '0%' 
        : `${Math.round(this.doneRate * 100)}%`
    },
    hasDiaryData() {
      const diaryList = getStorage('DIARY') || []
      return diaryList.length > 0
    }
  },
  onShow() {
    // 使用$nextTick确保DOM渲染完成后再初始化数据
    this.$nextTick(() => {
      this.initPageData()
    })
  },
  methods: {
    initPageData() {
      try {
        this.initTodoStats()
        this.initMoodCharts()
        this.initScheduleMoods()
      } catch (error) {
        console.error('初始化数据出错:', error)
      }
    },
    
    navigateToWriteDiary() {
      uni.navigateTo({
        url: '/pages/writeDiary/writeDiary'
      })
    },
    
    showMoodDetail(mood, dayIdx, slotIdx) {
      // 显示心情详情
      uni.showToast({
        title: `${this.weekdays[dayIdx]} ${['早晨', '下午', '晚上'][slotIdx]}: ${mood}`,
        icon: 'none',
        duration: 1500
      })
    },
    
    switchChart(chartType) {
      this.currentChart = chartType
      if (chartType === 'schedule' && !this.scheduleMoods.length) {
        this.initScheduleMoods()
      }
      // 切换图表时强制重绘
      this.$nextTick(() => {
        if (chartType === 'pie' || chartType === 'bar') {
          this.$forceUpdate()
        }
      })
    },

    initTodoStats() {
      try {
        const todoList = getStorage('TODO') || []
        this.totalTodo = todoList.length
        this.doneTodo = todoList.filter(item => item?.done).length
        this.doneRate = this.totalTodo === 0 ? 0 : this.doneTodo / this.totalTodo
      } catch (error) {
        console.error('初始化待办统计出错:', error)
        this.totalTodo = 0
        this.doneTodo = 0
        this.doneRate = 0
      }
    },

    initMoodCharts() {
      try {
        const diaryList = getStorage('DIARY') || []
        
        if (!this.hasDiaryData) {
          this.pieChartData = { series: [] }
          this.barChartData = { categories: [], series: [] }
          return
        }

        // 饼图数据处理
        const moodCount = Object.keys(this.moodColorMap).reduce((obj, mood) => {
          obj[mood] = 0
          return obj
        }, {})
        
        diaryList.forEach(diary => {
          if (diary?.tag && moodCount.hasOwnProperty(diary.tag)) {
            moodCount[diary.tag]++
          }
        })
        
        const pieSeries = Object.entries(moodCount)
          .filter(([mood, count]) => count > 0)
          .map(([mood, count]) => ({
            name: mood,
            data: count,
            color: this.moodColorMap[mood]
          }))
          
        this.pieChartData = {
          series: pieSeries
        }

        // 柱形图数据处理
        const last7Days = this.getLast7Days()
        const dailyMoodData = last7Days.reduce((obj, day) => {
          obj[day] = Object.keys(this.moodColorMap).reduce((moodObj, mood) => {
            moodObj[mood] = 0
            return moodObj
          }, {})
          return obj
        }, {})
        
        diaryList.forEach(diary => {
          if (diary?.date && diary?.tag) {
            const diaryDate = this.formatDateToMd(diary.date)
            if (last7Days.includes(diaryDate) && dailyMoodData[diaryDate].hasOwnProperty(diary.tag)) {
              dailyMoodData[diaryDate][diary.tag]++
            }
          }
        })
        
        const barSeries = Object.entries(this.moodColorMap)
          .map(([mood, color]) => ({
            name: mood,
            data: last7Days.map(day => dailyMoodData[day][mood] || 0),
            color: color
          }))
          .filter(series => series.data.some(num => num > 0))
          
        this.barChartData = {
          categories: last7Days,
          series: barSeries
        }
        
      } catch (error) {
        console.error('初始化心情图表出错:', error)
        this.pieChartData = { series: [] }
        this.barChartData = { categories: [], series: [] }
      }
    },

    initScheduleMoods() {
      try {
        const diaryList = getStorage('DIARY') || []
        const moodTypes = Object.keys(this.moodColorMap)
        
        this.scheduleMoods = Array(7).fill().map(() => Array(3).fill(''))
        
        diaryList.forEach(diary => {
          if (diary?.date && diary?.tag) {
            const date = new Date(diary.date)
            if (!isNaN(date.getTime())) {
              const dayOfWeek = date.getDay() || 7
              const dayIdx = dayOfWeek - 1
              if (dayIdx >= 0 && dayIdx < 7) {
                const slotIdx = Math.floor(Math.random() * 3)
                this.scheduleMoods[dayIdx][slotIdx] = diary.tag
              }
            }
          }
        })
        
        this.scheduleMoods = this.scheduleMoods.map(day => 
          day.map(slot => slot || moodTypes[Math.floor(Math.random() * moodTypes.length)])
        )
      } catch (error) {
        console.error('初始化课表心情出错:', error)
        // 初始化默认数据
        const moodTypes = Object.keys(this.moodColorMap)
        this.scheduleMoods = Array(7).fill().map(() => 
          Array(3).fill().map(() => moodTypes[Math.floor(Math.random() * moodTypes.length)])
        )
      }
    },

    getMoodColor(mood) {
      return this.moodColorMap[mood] || '#F5F5F5'
    },

    getLast7Days() {
      try {
        return Array(7).fill().map((_, i) => {
          const date = new Date()
          date.setDate(date.getDate() - 6 + i)
          return this.formatDateToMd(date)
        })
      } catch (error) {
        console.error('获取近7天日期出错:', error)
        return ['', '', '', '', '', '', '']
      }
    },

    formatDateToMd(date) {
      try {
        if (typeof date === 'string') {
          const parts = date.split('/')
          if (parts.length === 3) {
            const month = parseInt(parts[1], 10)
            const day = parseInt(parts[2], 10)
            return `${month}-${day}`
          }
        } else if (date instanceof Date) {
          return `${date.getMonth() + 1}-${date.getDate()}`
        }
        return ''
      } catch (error) {
        console.error('格式化日期出错:', error)
        return ''
      }
    }
  },
  // 添加错误捕获
  errorCaptured(err, vm, info) {
    console.error('组件内部错误:', err, info)
    return false
  }
}
</script>

<style scoped>
/* 全局样式变量 */
:root {
  --primary-gradient: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  --primary-color: #2196f3;
  --secondary-color: #1976d2;
  --text-primary: #333;
  --text-secondary: #666;
  --text-light: #999;
  --bg-white: rgba(255, 255, 255, 0.95);
  --shadow-sm: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  --shadow-md: 0 6rpx 30rpx rgba(0, 0, 0, 0.15);
  --border-radius: 20rpx;
  --transition: all 0.3s ease;
}

/* 动画效果 */
@keyframes fadeUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-up {
  animation: fadeUp 0.6s ease-out forwards;
  opacity: 0;
}

.animate-delay-1 {
  animation-delay: 0.1s;
}

.animate-delay-2 {
  animation-delay: 0.2s;
}

.animate-delay-3 {
  animation-delay: 0.3s;
}

.stats-page {
  padding: 20rpx;
  min-height: 100vh;
  background: var(--primary-gradient);
}

.page-header {
  background: var(--bg-white);
  border-radius: var(--border-radius);
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  box-shadow: var(--shadow-sm);
  backdrop-filter: blur(10rpx);
  text-align: center;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
  background: var(--primary-gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 24rpx;
  color: var(--text-light);
  display: block;
}

.todo-stats-card {
  background: var(--bg-white);
  border-radius: var(--border-radius);
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: var(--shadow-sm);
  backdrop-filter: blur(10rpx);
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 25rpx;
  display: block;
  color: var(--text-primary);
}

.todo-stats-row {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
}

.stats-item {
  text-align: center;
  position: relative;
  transition: var(--transition);
  padding: 20rpx;
  border-radius: 15rpx;
  background: rgba(33, 150, 243, 0.05);
  min-width: 200rpx;
}

.stats-item:active {
  transform: translateY(2rpx);
}

.stats-item:hover {
  background: rgba(33, 150, 243, 0.1);
}

.stats-icon {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  font-size: 32rpx;
  opacity: 0.3;
}

/* 进度条 */
.progress-section {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.08);
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.progress-text {
  font-size: 24rpx;
  color: var(--text-secondary);
  font-weight: 500;
}

.progress-percentage {
  font-size: 28rpx;
  font-weight: bold;
  color: var(--primary-color);
}

.progress-bar {
  width: 100%;
  height: 16rpx;
  background: rgba(33, 150, 243, 0.2);
  border-radius: 15rpx;
  overflow: hidden;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.08);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #2196f3, #1976d2);
  border-radius: 15rpx;
  transition: width 0.8s ease;
  box-shadow: 0 2rpx 8rpx rgba(33, 150, 243, 0.4);
}

.stats-num {
  font-size: 44rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 5rpx;
}

.done-num {
  color: #42b983;
}

.stats-label {
  color: var(--text-light);
  font-size: 24rpx;
}

.chart-tabs {
  display: flex;
  gap: 15rpx;
  flex-wrap: wrap;
  margin: 20rpx 0;
  justify-content: center;
}

.chart-tab {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx 28rpx;
  background: var(--bg-white);
  border-radius: 30rpx;
  font-size: 26rpx;
  box-shadow: var(--shadow-sm);
  transition: var(--transition);
  backdrop-filter: blur(10rpx);
  border: 2rpx solid transparent;
}

.chart-tab.active {
  background: var(--primary-gradient);
  color: white;
  transform: scale(1.05);
  box-shadow: var(--shadow-md);
  border-color: rgba(255, 255, 255, 0.3);
}

.chart-tab:active {
  transform: scale(0.98);
}

.tab-icon {
  font-size: 30rpx;
  display: inline-block;
}

.chart-container {
  background: var(--bg-white);
  border-radius: var(--border-radius);
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: var(--shadow-sm);
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 450rpx;
  align-items: center;
  backdrop-filter: blur(10rpx);
}

.chart-title {
  font-size: 32rpx;
  font-weight: bold;
  color: var(--text-primary);
  margin-bottom: 5rpx;
  display: block;
  text-align: center;
}

.chart-subtitle {
  font-size: 24rpx;
  color: var(--text-light);
  margin-bottom: 25rpx;
  display: block;
  text-align: center;
}

.no-data-tip {
  color: var(--text-light);
  font-size: 28rpx;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15rpx;
}

.no-data-icon {
  font-size: 60rpx;
  opacity: 0.5;
}

.empty-tip {
  background: var(--bg-white);
  border-radius: var(--border-radius);
  padding: 80rpx 30rpx;
  margin-bottom: 20rpx;
  text-align: center;
  box-shadow: var(--shadow-sm);
  backdrop-filter: blur(10rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15rpx;
}

.empty-icon {
  font-size: 100rpx;
  display: block;
  margin-bottom: 10rpx;
  opacity: 0.3;
}

.empty-text {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: var(--text-primary);
}

.empty-subtext {
  display: block;
  font-size: 24rpx;
  color: var(--text-light);
  margin-bottom: 30rpx;
}

.go-write-btn {
  background: var(--primary-gradient);
  color: white;
  border: none;
  padding: 15rpx 40rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  font-weight: bold;
  box-shadow: var(--shadow-md);
  transition: var(--transition);
}

.go-write-btn:active {
  transform: scale(0.95);
  box-shadow: var(--shadow-sm);
}

.schedule-container {
  background: var(--bg-white);
  border-radius: var(--border-radius);
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: var(--shadow-sm);
  backdrop-filter: blur(10rpx);
}

.schedule-header {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15rpx;
}

.weekday {
  width: 80rpx;
  text-align: center;
  font-weight: bold;
  color: var(--text-primary);
  font-size: 28rpx;
  margin-bottom: 15rpx;
  display: block;
  padding: 5rpx 0;
  border-bottom: 2rpx solid rgba(102, 126, 234, 0.3);
}

.schedule-grid {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
}

.day-column {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.mood-slot {
  width: 80rpx;
  height: 100rpx;
  border-radius: 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24rpx;
  font-weight: bold;
  text-shadow: 0 1rpx 3rpx rgba(0,0,0,0.3);
  transition: var(--transition);
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
  cursor: pointer;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.mood-slot:active {
  transform: scale(0.95);
  box-shadow: 0 1rpx 5rpx rgba(0,0,0,0.15);
}

.mood-slot:hover {
  transform: translateY(-3rpx);
  box-shadow: 0 4rpx 15rpx rgba(0,0,0,0.2);
}

.mood-text {
  padding: 5rpx;
  word-break: break-all;
  line-height: 1.3;
}

.time-slots {
  display: flex;
  justify-content: center;
  gap: 100rpx;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}

.time-slot {
  font-size: 24rpx;
  color: var(--text-secondary);
  font-weight: bold;
  background: rgba(102, 126, 234, 0.08);
  padding: 8rpx 15rpx;
  border-radius: 15rpx;
}

.mood-legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20rpx;
  margin-top: 25rpx;
  background: rgba(102, 126, 234, 0.08);
  padding: 20rpx;
  border-radius: 15rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 24rpx;
  color: var(--text-primary);
  background: rgba(255, 255, 255, 0.9);
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: var(--transition);
}

.legend-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.color-block {
  width: 25rpx;
  height: 25rpx;
  border-radius: 50%;
  box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.2);
  border: 2rpx solid white;
}
</style>